package xin.alum.aim;

import io.netty.channel.Channel;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.util.AttributeKey;
import lombok.SneakyThrows;
import org.springframework.stereotype.Component;
import xin.alum.aim.constant.AimPlatform;
import xin.alum.aim.groups.Sessions;
import xin.alum.aim.handler.AimReceiver;
import xin.alum.aim.model.Aim;
import xin.alum.aim.model.Events;

/**
 * @author Alum(alum @ live.cn)
 * @date 2021/8/7 9:53 1231321
 */
@Component
public class AimReciveService extends AimReceiver {

    String groupKey = "test_group";

    @Override
    public boolean onHandShake(Channel ch, FullHttpRequest req, FullHttpResponse res) {
        String tokens = (String) sessions.getAttr(ch, "token");
        res.setStatus(HttpResponseStatus.UNAUTHORIZED);
        return tokens != null;
    }

    /**
     * @param ch
     */
    @Override
    public void onHandShaked(Channel ch) {
        String token = ch.attr(AttributeKey.valueOf("token")).toString();
        sessions.bindUser(ch, token, AimPlatform.WINDOWS, "");
    }

    @SneakyThrows
    @Override
    public void onRecive(Channel ch, Events s) {
        long l = System.currentTimeMillis();
        Sessions sessions = groups.get(groupKey);
        if (!sessions.contains(ch)) {
            sessions = groups.bind(ch, groupKey);
        }

        final Events events = new Events(s.getKey(),s.getData());
//        Aim.Data.Builder b = Aim.Data.newBuilder();
//        b.(d.getAttrsMap());
        //b.putAttrs("uid", ch.attr(AimAttr.UID).get());
//        events.setData(s.getData());
        groups.sends(groupKey, events);
//        ChannelGroupFuture f = sessions.sends(events);
//        int r = sessions.size();
//        f.addListener(t -> {
//            if (s.refCnt() > 0) {
//                s.release(s.refCnt());
//            }
//            long c = System.currentTimeMillis() - l;
//            if (f.isPartialFailure()) {
//                logger.warn("{}向【{}】发【{}】人用时-{}", ch, groupKey, r, c);
//            }
//        });

    }
}
